package com.jcj.endecoder;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  服务器端,分隔符解码器DelimiterBasedFrameDecoder对发送接、收数据的处理
 */
@ChannelHandler.Sharable
public class HandlerServerDelimiterBased extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //处理接收到的数据,并反馈消息到客户端
        String strInfo = (String) msg;
        System.out.println("收到客户端消息: " + strInfo.trim());

        //写入并发送信息到远端(客户端)
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss SSS");//设置日期格式
        String strDate = df.format(new Date());
        String strMsg = "你好,客户端: " + strDate+"$";
        System.out.println("向客户端反馈的消息:" + strMsg);
        ctx.writeAndFlush(Unpooled.copiedBuffer(strMsg, CharsetUtil.UTF_8));

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //出现异常的时候执行的动作(打印并关闭通道)
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 新建立连接时触发的动作
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //System.out.println("打印channel:"+channel);
        //System.out.println("运行类型:"+channel.getClass());
        System.out.println("客户端: " + channel.remoteAddress() + "已连接上来");
    }

    /**
     * 连接断开时触发的动作
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("客户端: " + channel.remoteAddress() + "已断开");
    }

    /**
     * 通道处于活动状态触发的动作,该方法只会在通道建立时调用一次
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("客户端: " + channel.remoteAddress() + "在线");
    }

    /**
     * 通道处于非活动状态触发的动作,该方法只会在通道失效时调用一次
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("客户端: " + channel.remoteAddress() + "掉线");
    }
}
